package com.wjs.juc.Interrupt;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;


public class InterruptDemo1 {
    static volatile boolean isStop=false;
    static AtomicBoolean isFlag=new AtomicBoolean(false);
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("t1 线程被中断");
                    break;
                }
                System.out.println("t1 hello interrupt");
            }
        }, "t1");
        t1.start();
        TimeUnit.SECONDS.sleep(3);
        t1.interrupt();
    }

    /**
     * AtomicBoolean实现线程中断
     */
    private static void ByAtomicBoolean() {
        new Thread(()->{
            while (true){
                if(isFlag.get()){
                    System.out.println("t1 线程停止");
                    break;
                }
                System.out.println("hello t1");
            }
        },"t1").start();
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
           isFlag.set(true);
        },"t2").start();
    }

    /**
     * volatile实现线程中断
     */
    private static void Byvolatile(){
        new Thread(()->{
            while (true){
                if(isStop){
                    System.out.println("t1 线程停止");
                    break;
                }
                System.out.println("hello t1");
            }
        },"t1").start();
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            isStop=true;
        },"t2").start();
    }
}
